package org.example.proxy.jdk;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Proxy;

/**
 * 代理类必须实现接口
 */
public class JDKDynamicProxyDemo {
    @BeforeAll
    public static void beforeAll() {
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
    }

    @Test
    @DisplayName("AOP示例，利用JDK进行代理")
    public void test() {
        //被代理对象
        Dog dog = new Dog();
        //动态代理对象
        AnimalInvocationHandler<Animal> animalInvocationHandler = new AnimalInvocationHandler<>();
        Animal proxy = animalInvocationHandler.bind(dog);
        proxy.eat();
        System.out.println("原来：" + dog);//这里的toString不会被代理
        System.out.println("代理：" + proxy);//这里的toString会被代理

        Assertions.assertFalse(Proxy.isProxyClass(dog.getClass()));
        Assertions.assertTrue(Proxy.isProxyClass(proxy.getClass()));
    }
}
